package com.cn.tous.common.security.utils;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;

/**
 * @author mengwei
 * @description SecurityUtils
 * @createDate 2025/7/26 12:20
 */
public class SecurityUtils {


    /**
     * 获取当前登录用户的用户名
     */
    public static String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return null;
        }

        // 处理JWT认证
        if (authentication instanceof JwtAuthenticationToken) {
            JwtAuthenticationToken jwtAuth = (JwtAuthenticationToken) authentication;
            // 从JWT中获取用户名，通常存储在"sub"声明中
            return jwtAuth.getToken().getSubject();
        }

        // 处理普通表单认证
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        }

        if (principal instanceof String) {
            return (String) principal;
        }

        return null;
    }

    /**
     * 获取当前登录用户的认证信息
     */
    public static Authentication getCurrentAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 判断当前用户是否拥有指定角色
     */
    public static boolean hasRole(String role) {
        // Spring Security角色默认带有ROLE_前缀
        String roleWithPrefix = "ROLE_" + role;
        return hasAuthority(roleWithPrefix);
    }

    /**
     * 判断当前用户是否拥有指定权限
     */
    public static boolean hasAuthority(String authority) {
        Authentication authentication = getCurrentAuthentication();
        if (authentication == null) {
            return false;
        }

        return authentication.getAuthorities().stream()
                .anyMatch(a -> a.getAuthority().equals(authority));
    }

    /**
     * 从JWT令牌中获取自定义声明
     */
    public static Object getJwtClaim(String claimName) {
        Authentication authentication = getCurrentAuthentication();
        if (authentication instanceof JwtAuthenticationToken) {
            JwtAuthenticationToken jwtAuth = (JwtAuthenticationToken) authentication;
            return jwtAuth.getToken().getClaim(claimName);
        }
        return null;
    }
}
